<template>
  <div class="app-container" ref="container">
    <el-space alignment="flex-start">
      <el-scrollbar>
        <div class="tree" justify="space-between" :style="{ width: treeWidth + 'px' }" ref="treeRef">
          <Tree :treeData="treeData" :defaultProps="defaultProps" nodeKey="id" :currentNodeKey="currentKey"
            @handleNodeClick="handleNodeClick" v-loading="treeLoading" :isShowTitle="true" v-model:isExpand="isExpand" />
          <el-empty v-if="treeData.length == 0" description="暂无数据" />
        </div>
      </el-scrollbar>
      <!-- <el-scrollbar> -->
        <div class="queryList" :style="{ width: queryListWidth + 'px' }" ref="list">
          <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="160px">
            <el-row>
              <el-form-item label="省" prop="provinceId">
                <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                  <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="市" prop="cityId">
                <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
                  <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="区/县" prop="countyId">
                <el-select v-model="queryParams.countyId" placeholder="请选择区/县" clearable>
                  <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="项目名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入项目名称" clearable></el-input>
              </el-form-item>
              <el-form-item label="项目状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择" clearable>
                  <el-option label="进行中" value="0"></el-option>
                  <el-option label="已完成" value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="项目编码" prop="number">
                <el-input v-model="queryParams.number" placeholder="请输入项目编码" clearable></el-input>
              </el-form-item>
              <el-form-item label=" ">
                <el-button type="primary" @click="getList">查询</el-button>
                <el-button plain @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>

          <el-divider></el-divider>

          <el-row :gutter="10" class="mb8" style="float:left">
            <el-col :span="1.5">
              <el-button type="primary" icon="Plus" @click="handleAdd">新建</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button plain icon="Delete" @click="handleFinish">项目结束</el-button>
            </el-col>
          </el-row>

          <el-table v-loading="loading" :data="dataList" @selection-change="selectChange" stripe>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="项目编码" align="center" prop="number">
              <template #default="{ row }">
                <el-link type="primary" :underline="false" @click="viewOrUpdateProject(row.id)">{{ row.number
                }}</el-link>
              </template>
            </el-table-column>
            <el-table-column label="项目名称" align="center" prop="name" />
            <el-table-column label="所属省份" align="center" prop="province" />
            <el-table-column label="城市名称" align="center" prop="city" />
            <el-table-column label="区县名称" align="center" prop="county" />
            <el-table-column label="项目来源" align="center" prop="source" />
            <el-table-column label="项目类型" align="center" prop="type" />
            <el-table-column label="专题数量" align="center" prop="spNumber" />
            <el-table-column label="项目负责人" align="center" prop="leader" />
            <el-table-column label="技术负责人" align="center" prop="technicalLeader" />
            <el-table-column label="项目状态" align="center" prop="status">
              <template #default="{ row }">
                <span v-if="row.status == '0'">进行中</span>
                <span v-else-if="row.status == '1'">已完成</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="{ row }">
                <el-button type="text" @click="handleUpdate(row.id, row.spNumber)">新建专题</el-button>
                <el-button type="text" @click="handleDelete(row)" v-if="row.status != '1'">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.rows" @pagination="getList" />
        </div>
      <!-- </el-scrollbar> -->
    </el-space>

    <el-drawer v-model="projectDrawer" size="45%" :show-close="false" @open="openProject" @close="closeProject">
      <template #title>
        <h2><svg-icon icon-class="list"></svg-icon><span style="padding-left: 15px">项目管理</span></h2>
        <template v-if="!projectIsEdit">
          <el-button plain @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">保存</el-button>
        </template>
        <template v-else>
          <el-button plain @click="cancelClick">关闭</el-button>
        </template>

      </template>
      <template #default>
        <div>
          <el-form :model="projectForm" ref="projectRef" :rules="projectRules" :inline="true" label-width="110px"
            :disabled="projectIsEdit">
            <el-row justify="space-between">
              <el-form-item label="所属省份" prop="provinceId">
                <el-select v-model="projectForm.provinceId" placeholder="请选择所属省份" @change="chooseProvince" clearable>
                  <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="城市名称" prop="cityId">
                <el-select v-model="projectForm.cityId" placeholder="请选择城市名称" @change="chooseCity" clearable>
                  <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="区县名称" prop="countyId">
                <el-select v-model="projectForm.countyId" placeholder="请选择区县名称" @change="chooseCounty" clearable>
                  <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="行政代码" prop="adCode">
                <el-input v-model="projectForm.adCode" placeholder="请输入行政代码" clearable disabled></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="项目编码" prop="number">
                <el-input v-model="projectForm.number" placeholder="请输入项目编码" clearable disabled></el-input>
              </el-form-item>
              <el-form-item label="项目名称" prop="name">
                <el-input v-model="projectForm.name" placeholder="请输入项目名称" clearable></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="项目类型" prop="type">
                <el-select v-model="projectForm.type" placeholder="请选择项目类型" clearable>
                  <el-option label="城市活动断层探测" value="城市活动断层探测"></el-option>
                  <el-option label="活动断层填图" value="活动断层填图"></el-option>
                  <el-option label="断层活动性鉴定" value="断层活动性鉴定"></el-option>
                  <el-option label="地震灾害风险普查" value="地震灾害风险普查"></el-option>
                  <el-option label="其他" value="其他"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="项目来源" prop="source">
                <el-select v-model="projectForm.source" placeholder="请选择项目来源" clearable>
                  <el-option label="地方项目" value="地方项目"></el-option>
                  <el-option label="中央项目" value="中央项目"></el-option>
                  <el-option label="地方项目-中央配套" value="地方项目-中央配套"></el-option>
                  <el-option label="其他" value="其他"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="项目代码" prop="code">
                <el-input v-model="projectForm.code" placeholder="请输入项目代码" clearable disabled></el-input>
              </el-form-item>
              <el-form-item label="项目单位" prop="pany">
                <el-input v-model="projectForm.pany" placeholder="请输入项目单位" clearable></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="联系方式" prop="contact">
                <el-input v-model="projectForm.contact" placeholder="请输入联系方式" clearable></el-input>
              </el-form-item>
              <el-form-item label="项目负责人" prop="leader">
                <el-input v-model="projectForm.leader" placeholder="请输入项目负责人" clearable readonly
                  @click="openSelectUser('leader')"></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="监理单位" prop="supervisionUnits">
                <el-input v-model="projectForm.supervisionUnits" placeholder="请输入监理单位" clearable></el-input>
              </el-form-item>
              <el-form-item label="技术负责人" prop="technicalLeader">
                <el-input v-model="projectForm.technicalLeader" placeholder="请输入技术负责人" clearable
                  @click="openSelectUser('technicalLeader')"></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="创建人单位" prop="founderPany">
                <el-input v-model="projectForm.founderPany" placeholder="请输入创建人单位" clearable disabled></el-input>
              </el-form-item>
              <el-form-item label="专题数量" prop="spNumber">
                <el-select v-model="projectForm.spNumber" placeholder="请选择专题数量" clearable>
                  <el-option v-for="item in 21" :key="item - 1" :label="item - 1" :value="item - 1">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="创建人" prop="founder">
                <el-input v-model="projectForm.founder" placeholder="请输入创建人" clearable disabled></el-input>
              </el-form-item>
              <el-form-item label="项目验收时间" prop="receptionTime">
                <el-date-picker v-model="projectForm.receptionTime" type="date" placeholder="请选择项目验收时间"
                  value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="项目简介" prop="briefIntro" style="width:100%">
                <el-input v-model="projectForm.briefIntro" placeholder="请输入项目简介" :autosize="{ minRows: 5 }"
                  type="textarea" clearable show-word-limit maxlength="500"></el-input>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
      </template>
    </el-drawer>

    <el-dialog v-model="subjectDialog" :title="subjectForm.name" @close="closeSubject">
      <el-form :model="subjectForm" ref="projectRef" label-width="100px" disabled>
        <el-row justify="space-between">
          <el-col :span="24">
            <el-form-item label="专题编码：" prop="coding">{{ subjectForm.coding }}</el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between">
          <el-col :span="10">
            <el-form-item label="数据入库员：" prop="dataIqa">{{ subjectForm.dataIqa }}</el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="数据质检员：" prop="dataQc">{{ subjectForm.dataQc }}</el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between">
          <el-col :span="10">
            <el-form-item label="专题负责人：" prop="studyDirector">{{ subjectForm.studyDirector }}</el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="技术负责人：" prop="technicalLeader">{{ subjectForm.technicalLeader }}</el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between">
          <el-col :span="10">
            <el-form-item label="专题状态：" prop="status">
              <span v-if="subjectForm.status == '0'">进行中</span>
              <span v-else-if="subjectForm.status == '1'">已完成</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="专题简介：" prop="briefIntro">{{ subjectForm.briefIntro }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button plain @click="subjectDialog = false">取消</el-button>
          <el-button type="primary" @click="updateSubject(subjectForm.id)">
            <span v-if="subjectForm.status == '0'">修改</span>
            <span v-else-if="subjectForm.status == '1'">查看</span>
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 人员选择对话框 -->
    <select-user ref="selectRef" :multi="2" v-model:show="openSelect" @getSelectList="getSelectList" />
    <router-view></router-view>
  </div>
</template>
<script setup name="project">
import { getProvince, getChildArea } from "@/api/system/division"
import { save, getAll, deleteList, getById, update, getNumber, getDivisionCode, getCode, getTreeList, endProject, changePermission } from '@/api/projectManage/project'
import { getById as getSubject } from '@/api/projectManage/subject'
import SelectUser from '@/components/SelectUser/index'
import { ElMessageBox } from 'element-plus'
import Tree from '@/components/Tree'
import useTreeSpace from '@/hooks/useTreeSpace'

const queryData = reactive({
  queryParams: {
    page: 1,
    rows: 10
  },
  provinceData: [],
  cityData: [],
  areaData: [],
  total: 0
})
const { queryParams, provinceData, cityData, areaData, total } = toRefs(queryData)
const tableData = reactive({
  loading: false,
  dataList: []
})
const { loading, dataList } = toRefs(tableData)
const initForm = () => ({})
const projectData = reactive({
  projectDrawer: false,
  projectForm: initForm(),
  projectIsEdit: false
})
const projectRules = reactive({
  provinceId: [{ required: true, message: '请选择所属省份', trigger: 'change' }],
  number: [{ required: true, message: '请输入项目编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
  source: [{ required: true, message: '请选择项目来源', trigger: 'change' }],
  code: [{ required: true, message: '请输入项目代码', trigger: 'blur' }],
  pany: [{ required: true, message: '请输入项目单位', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  leader: [{ required: true, message: '请选择项目负责人', trigger: 'change' }],
  supervisionUnits: [{ required: true, message: '请输入监理单位', trigger: 'blur' }],
  technicalLeader: [{ required: true, message: '请选择技术负责人', trigger: 'change' }],
  founderPany: [{ required: true, message: '请输入创建人单位', trigger: 'blur' }],
  spNumber: [{ required: true, message: '请选择专题数量', trigger: 'change' }],
  founder: [{ required: true, message: '请输入创建人', trigger: 'blur' }],
  receptionTime: [{ required: true, message: '请选择项目验收时间', trigger: 'change' }],
  briefIntro: [{ required: true, message: '请输入项目简介', trigger: 'blur' }],
})
const { projectDrawer, projectForm, projectIsEdit } = toRefs(projectData)
const subjectData = reactive({
  subjectDialog: false,
  subjectForm: {}
})
const { subjectDialog, subjectForm } = toRefs(subjectData)

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()

// 选择人员弹窗
const openSelect = ref(false)
let selectPerson = ''
const openSelectUser = (type) => {
  openSelect.value = true
  selectPerson = type
}
const getSelectList = (arr) => {
  let personName = arr.map(item => item.realName).join(',')
  let personId = arr.map(item => item.orgUser.userId).join(',')
  projectForm.value[selectPerson] = personName
  projectForm.value[selectPerson + 'Id'] = personId
}

onMounted(() => {
  getProvinceData()
  getList()
})

// 获取树结构
const isExpand = ref(true)
const treeWidth = computed(() => isExpand.value ? 200 : 20)
const { container, treeRef, queryListWidth } = useTreeSpace(treeWidth.value)
const treeData = ref([])
const treeLoading = ref(false)
const defaultProps = {
  children: 'list',
  label: 'name',
}
const getTreeData = () => {
  treeLoading.value = true
  getTreeList().then(res => {
    treeData.value = res.data
    treeLoading.value = false
  })
}
watch(dataList, () => {
  getTreeData()
}, { deep: true })
// 树形结构点击事件
const curProjectId = ref('')
const handleNodeClick = (data, node) => {
  if (node.level === 1) {
    viewOrUpdateProject(data.id)
  } else if (node.level === 2) {
    curProjectId.value = node.parent.data.id
    subjectDialog.value = true
    getSubjectDetail(data.id)
  }
}
// 查询专题详情
const getSubjectDetail = (id) => {
  getSubject(id).then(res => {
    subjectForm.value = res.data
  })
}
// 省市县
const getProvinceData = () => {
  getProvince().then(res => {
    if (res.code == 200) {
      provinceData.value = res.data
    }
  })
}
const chooseProvince = (value) => {
  queryParams.value.cityId = null
  queryParams.value.countyId = null
  queryParams.value.city = null
  queryParams.value.county = null
  cityData.value = []
  areaData.value = []
  getChildArea(value).then(response => {
    cityData.value = response.data
  })
  projectForm.value.province = provinceData.value.find(item => item.value == value).name
  getDivisionCode(value).then(res => {
    projectForm.value.adCode = res.data
  })
}
const chooseCity = (value) => {
  queryParams.value.countyId = null
  queryParams.value.county = null
  areaData.value = []
  getChildArea(value).then(response => {
    areaData.value = response.data
  })
  projectForm.value.city = cityData.value.find(item => item.id == value).name
  getDivisionCode(value).then(res => {
    projectForm.value.adCode = res.data
  })
}
const chooseCounty = (value) => {
  projectForm.value.county = areaData.value.find(item => item.id == value).name
  getDivisionCode(value).then(res => {
    projectForm.value.adCode = res.data
  })
}
// 查询
const getList = () => {
  loading.value = true
  getAll(queryParams.value).then(res => {
    dataList.value = res.data.rows
    total.value = res.data.total
    loading.value = false
  })
}
// 重置
const resetQuery = () => {
  queryParams.value.page = 1
  proxy.resetForm('queryRef')
  getList()
}
// 新建
const handleAdd = () => {
  projectDrawer.value = true
  projectForm.value.founder = localStorage.getItem('userName')
  projectForm.value.founderPany = localStorage.getItem('orgName')
  getNumber().then(res => {
    projectForm.value.number = res.data
  })
}
// 根据项目类型和行政代码获取项目代码
watchEffect(() => {
  if (projectForm.value.type && projectForm.value.adCode) {
    let params = { type: projectForm.value.type, adCode: projectForm.value.adCode }
    getCode(params).then(res => {
      projectForm.value.code = res.data
    })
  }
})
// 修改新建专题/查看修改专题
const handleUpdate = (id, num) => {
  router.push({ name: 'subject', query: { id, num } })
}
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm('项目下所有数据将被删除，是否确定删除?').then(() => {
    return deleteList(row.id)
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    getList()
  })
}
// 项目结束
const handleFinish = () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning('请至少选择一条数据！')
    return
  }
  ElMessageBox.confirm(
    `<p>请确定：</p>
    <p>1、是否所有子专题已完成数据采集工作；</p>
    <p>2、是否所有子专题已完成数据质检工作；</p>
    <p>结束后，将无法进行数据上传、质检操作。</p>`,
    '提示',
    { dangerouslyUseHTMLString: true, cancelButtonClass: 'is-plain', }
  ).then(() => {
    return endProject(ids.value)
  }).then(res => {
    getList()
  })
    .catch((action) => { })
}
// 多选
const ids = ref([])
const selectChange = (selection) => {
  ids.value = selection.map(item => item.id)
}
// 查看项目
const viewOrUpdateProject = async (id) => {
  projectDrawer.value = true
  let permission = await changePermission(id)
  projectIsEdit.value = !permission.data
  getById(id).then(res => {
    projectForm.value = res.data
    // 获取市县
    getChildArea(projectForm.value.provinceId).then(response => {
      cityData.value = response.data
    })
    getChildArea(projectForm.value.cityId).then(response => {
      areaData.value = response.data
    })
    if (projectForm.value.status == '1') {
      projectIsEdit.value = true
    }
  })
}

// 取消
const cancelClick = () => {
  projectDrawer.value = false
  proxy.resetForm('projectRef')
}
// 保存
const confirmClick = () => {
  proxy.$refs['projectRef'].validate((valid, fields) => {
    if (valid) {
      if (projectForm.value.id) {
        update(projectForm.value).then(res => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('修改成功！')
            projectDrawer.value = false
            getList()
          }
        })
      } else {
        save(projectForm.value).then(res => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('保存成功！')
            projectDrawer.value = false
            getList()
          }
        })
      }
    } else {
      proxy.$refs['projectRef'].scrollToField(Object.keys(fields)[0])
    }
  })
}
const openProject = () => {
  nextTick(() => {
    proxy.$refs['projectRef'].clearValidate()
  })
}
const closeProject = () => {
  proxy.resetAllForm(projectForm.value, initForm())
  projectIsEdit.value = false
}
const closeSubject = () => {
  curProjectId.value = ''
}
// 专题修改/查看
const updateSubject = (subId) => {
  subjectDialog.value = false
  router.push({ name: 'subject', query: { id: curProjectId.value }, params: { subId } })
}
const currentKey = ref()
watch(() => route.params.proId, (newVal) => {
  if (newVal) {
    currentKey.value = newVal
    viewOrUpdateProject(newVal)
  }
}, { immediate: true })

</script>
<style scoped lang="scss">
.app-container {
  height: 100%;

  .el-space {
    height: 100%;
    width: 100%;

    :deep(.el-space__item) {
      height: 100%;
    }

    .tree,
    .queryList {
      display: inline-block;
      height: 100%;
      overflow-y: auto;
    }
  }
}
</style>